package pe.edu.upc.dsd.deal.web;

import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;

import org.springframework.beans.factory.annotation.Autowired;

import pe.edu.upc.dsd.deal.service.Deal;
import pe.edu.upc.dsd.deal.service.DealService;

import com.google.gson.Gson;

@Path("/deal")
@Consumes({ MediaType.APPLICATION_JSON, MediaType.TEXT_PLAIN })
@Produces({ MediaType.APPLICATION_JSON, MediaType.TEXT_PLAIN })
public class DealController {

	@Autowired
	private DealService dealService;

	public void setDealService(DealService dealService) {
		this.dealService = dealService;
	}

	private Gson gson = new Gson();

	@GET
	public Response findAll() throws Exception {
		return Response.ok(gson.toJson(dealService.findAll())).build();
	}

	@Path("/{isbn}")
	@GET
	public Response find(@PathParam("isbn") String isbn) {
		try {
			Deal deal = dealService.find(isbn);
			if (deal == null) {
				return Response.status(Status.INTERNAL_SERVER_ERROR).entity("La oferta no existe").build();
			}
			return Response.ok(gson.toJson(deal)).build();
		} catch(Exception e) {
			return Response.status(Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
		}
	}

	@Path("/{isbn}")
	@DELETE
	public Response delete(String isbn) {
		Deal deal = new Deal();
		deal.setIsbn(isbn);
		try {
			dealService.delete(deal);
		} catch (Exception e) {
			return Response.status(Status.INTERNAL_SERVER_ERROR).entity("Error al eliminar la oferta").build();
		}
		return Response.ok().build();
	}

	@POST
	public Response save(String json) {
		try {
			dealService.save(gson.fromJson(json, Deal.class));
		} catch (Exception e) {
			return Response.status(Status.INTERNAL_SERVER_ERROR).entity("Error al guardar la oferta").build();
		}
		System.out.println("Save");
		return Response.ok().build();
	}

	@PUT
	public Response update(String json) {
		try {
			dealService.update(gson.fromJson(json, Deal.class));
		} catch (Exception e) {
			return Response.status(Status.INTERNAL_SERVER_ERROR).entity("Error al guardar la oferta").build();
		}
		System.out.println("update");
		return Response.ok().build();
	}
}
